package com.huan.drools;

import org.kie.api.KieServices;
import org.kie.api.event.rule.DebugRuleRuntimeEventListener;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;

/**
 * drools 测试类
 */
public class DroolsApplication {
    public static void main(String[] args) {
        equalsBehaviorIdentity();
        System.out.println("==========================");
        equalsBehaviorEquality();
    }

    private static void equalsBehaviorEquality() {
        KieServices kieServices = KieServices.get();
        KieContainer kieContainer = kieServices.getKieClasspathContainer();
        KieSession kieSession = kieContainer.newKieSession("ksession-02");
        kieSession.addEventListener(new DebugRuleRuntimeEventListener());

        Person p1 = new Person("zhangsan", 20, "湖北罗田");
        Person p2 = new Person("zhangsan", 20, "湖北黄冈罗田");

        // Equality 模式下，会比较对象的equal和hashcode方法，如果相等，则说明对象已经在工作内存中了，因此下方插入的p1,p2在工作内存中只会存在一个
        FactHandle factHandle1 = kieSession.insert(p1);
        FactHandle factHandle2 = kieSession.insert(p2);
        FactHandle factHandle3 = kieSession.insert(p2);
        kieSession.fireAllRules();

        System.out.println(factHandle1 == factHandle2);
        System.out.println(factHandle2 == factHandle3);
        System.out.println(kieSession.getFactHandle(p1) == kieSession.getFactHandle(p2));
        System.out.println(factHandle1 == kieSession.getFactHandle(new Person("zhangsan", 20, "湖北")));

        kieSession.dispose();
    }

    private static void equalsBehaviorIdentity() {
        KieServices kieServices = KieServices.get();
        KieContainer kieContainer = kieServices.getKieClasspathContainer();
        KieSession kieSession = kieContainer.newKieSession("ksession-01");
        kieSession.addEventListener(new DebugRuleRuntimeEventListener());

        Person p1 = new Person("zhangsan", 20, "湖北罗田");
        Person p2 = new Person("zhangsan", 20, "湖北黄冈罗田");

        FactHandle factHandle1 = kieSession.insert(p1);
        // Identity 模式下 2次插入p2对象，工作内存中只会存在一个，因此factHandle2=factHandle3
        FactHandle factHandle2 = kieSession.insert(p2);
        FactHandle factHandle3 = kieSession.insert(p2);
        kieSession.fireAllRules();

        System.out.println(factHandle1 == factHandle2);
        System.out.println(factHandle2 == factHandle3);
        System.out.println(kieSession.getFactHandle(p1) == kieSession.getFactHandle(p2));
        System.out.println(factHandle1 == kieSession.getFactHandle(new Person("zhangsan", 20, "湖北")));

        kieSession.dispose();
    }
}
